<template>
  <!-- z-paging 列表：支持下拉刷新与触底加载 -->
  <z-paging
    ref="paging"
    v-model="dataList"
    loading-more-no-more-text="我也是有底线的！"
    @query="queryList"
  >
    <template #loading>
      <uni-load-more status="loading"></uni-load-more>
    </template>

    <view class="title">通讯录</view>
    <view v-for="u in dataList" :key="u.id" class="item" @click="toDetail(u)">
      <image class="avatar" :src="u.avatarUrl || defaultAvatar" mode="cover" />
      <view class="info">
        <view class="name">{{ u.account || u.account }}</view>
      </view>
    </view>
  </z-paging>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { pageSysUsers } from '@/api/chat/user'
import { createSingleSession } from '@/api/chat/session'

const paging = ref(null)
const dataList = ref<any[]>([])
const defaultAvatar = '/static/logo.png'

function getUserId(): number | undefined {
  try {
    const u = uni.getStorageSync('user')
    return u?.id
  } catch { return undefined }
}

/**
 * z-paging 的数据加载函数
 * pageNo/pageSize 由 z-paging 统一管理
 */
async function queryList(pageNo: number, pageSize: number) {
  console.log('queryList', pageNo, pageSize)
  try {
    const res = await pageSysUsers({ pageNum: pageNo, pageSize })
    const data = res?.data ?? res
    const list = data?.list || []
    // 将本次加载的数据与是否还有更多回传给 z-paging
    paging.value.completeByTotal(list, data?.total)
  } catch (e:any) {
    uni.showToast({ title: e?.message || '加载用户失败', icon: 'none' })
    paging.value.complete([], false)
  }
}

const toDetail = (u: any) => {
  if (!u || !u.id) return
  const userA = getUserId()
  const userB = u.id
  if (!userA) {
    uni.showToast({ title: '请先登录', icon: 'none' })
    setTimeout(() => {
      uni.switchTab({ url: '/pages/view/MineTab' })
    }, 500)
    return
  }
  uni.showModal({
    title: '添加聊天',
    content: `确定与 ${u.nickname || u.account || ('用户' + userB)} 发起单聊吗？`,
    success: async (res:any) => {
      if (res.confirm) {
        try {
          await createSingleSession({ userA, userB })
          uni.showToast({ title: '创建成功', icon: 'success' })
          setTimeout(() => {
            uni.switchTab({ url: '/pages/view/ChatTab' })
          }, 400)
        } catch (e:any) {
          uni.showToast({ title: e?.message || '创建失败', icon: 'none' })
        }
      }
    }
  })
}




</script>

<style>
.container { padding: 24rpx; }
.title { font-size: 32rpx; font-weight: 600; margin: 16rpx 24rpx; }
.item { display: flex; align-items: center; padding: 16rpx 24rpx; border-bottom: 1px solid #eee; }
.avatar { width: 80rpx; height: 80rpx; border-radius: 50%; background: #f0f0f0; }
.info { margin-left: 16rpx; }
.name { font-size: 30rpx; color: #333; }
.meta { font-size: 24rpx; color: #999; margin-top: 6rpx; }
</style>